# stories/admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import CustomUser, StoryCategory, Story, Comment, Rating, SensitiveWord


@admin.register(CustomUser)
class CustomUserAdmin(UserAdmin):
    """自定义用户管理界面"""
    list_display = ('username', 'email', 'phone', 'is_admin', 'date_joined', 'is_active')
    list_filter = ('is_active', 'is_staff', 'is_superuser', 'is_admin', 'date_joined')
    search_fields = ('username', 'email', 'phone')
    ordering = ('-date_joined',)
    
    fieldsets = UserAdmin.fieldsets + (
        ('扩展信息', {'fields': ('phone', 'avatar', 'bio', 'is_admin')}),
    )
    
    add_fieldsets = UserAdmin.add_fieldsets + (
        ('扩展信息', {'fields': ('email', 'phone', 'avatar', 'bio', 'is_admin')}),
    )


@admin.register(StoryCategory)
class StoryCategoryAdmin(admin.ModelAdmin):
    """故事分类管理界面"""
    list_display = ('name', 'description', 'created_at')
    search_fields = ('name', 'description')
    ordering = ('name',)
    list_per_page = 20


@admin.register(Story)
class StoryAdmin(admin.ModelAdmin):
    """故事管理界面"""
    list_display = ('title', 'author', 'category', 'status', 'view_count', 'average_rating', 'created_at')
    list_filter = ('status', 'category', 'created_at', 'updated_at')
    search_fields = ('title', 'content', 'author__username')
    ordering = ('-created_at',)
    list_per_page = 20
    
    fieldsets = (
        ('基本信息', {
            'fields': ('title', 'author', 'category', 'status')
        }),
        ('内容', {
            'fields': ('content', 'cover_image')
        }),
        ('审核信息', {
            'fields': ('reviewed_at', 'reviewed_by', 'rejection_reason'),
            'classes': ('collapse',)
        }),
        ('统计信息', {
            'fields': ('view_count', 'average_rating', 'rating_count'),
            'classes': ('collapse',)
        })
    )
    
    readonly_fields = ('view_count', 'average_rating', 'rating_count', 'reviewed_at', 'reviewed_by', 'rejection_reason')
    
    def save_model(self, request, obj, form, change):
        """保存时自动设置作者"""
        if not change:  # 新创建的故事
            obj.author = request.user
        super().save_model(request, obj, form, change)


@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
    """评论管理界面"""
    list_display = ('story', 'author', 'content_preview', 'created_at', 'parent')
    list_filter = ('created_at', 'story__category')
    search_fields = ('content', 'author__username', 'story__title')
    ordering = ('-created_at',)
    list_per_page = 50
    
    def content_preview(self, obj):
        """显示评论内容预览"""
        return obj.content[:50] + '...' if len(obj.content) > 50 else obj.content
    content_preview.short_description = '评论内容'
    
    def get_queryset(self, request):
        """优化查询"""
        return super().get_queryset(request).select_related('author', 'story', 'parent')


@admin.register(Rating)
class RatingAdmin(admin.ModelAdmin):
    """评分管理界面"""
    list_display = ('story', 'user', 'score', 'created_at')
    list_filter = ('score', 'created_at')
    search_fields = ('story__title', 'user__username')
    ordering = ('-created_at',)
    list_per_page = 50
    
    def get_queryset(self, request):
        """优化查询"""
        return super().get_queryset(request).select_related('story', 'user')


@admin.register(SensitiveWord)
class SensitiveWordAdmin(admin.ModelAdmin):
    """敏感词管理界面"""
    list_display = ('word', 'is_active', 'created_at', 'updated_at')
    list_filter = ('is_active', 'created_at')
    search_fields = ('word',)
    ordering = ('word',)
    list_per_page = 50
    
    actions = ['activate_words', 'deactivate_words']
    
    def activate_words(self, request, queryset):
        """激活选中的敏感词"""
        queryset.update(is_active=True)
        self.message_user(request, f'已激活 {queryset.count()} 个敏感词')
    activate_words.short_description = '激活选中的敏感词'
    
    def deactivate_words(self, request, queryset):
        """停用选中的敏感词"""
        queryset.update(is_active=False)
        self.message_user(request, f'已停用 {queryset.count()} 个敏感词')
    deactivate_words.short_description = '停用选中的敏感词'


# 自定义admin站点标题
admin.site.site_header = 'AI故事生成网站管理后台'
admin.site.site_title = 'AI故事管理'
admin.site.index_title = '欢迎使用AI故事生成网站管理系统'